package com.com.baidu.ai.aip;

import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.utils.FileUtil;
import com.baidu.ai.aip.utils.HttpUtil;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 重要提示代码中所需工具类
 * FileUtil,Base64Util,HttpUtil,GsonUtils请从
 * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
 * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
 * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
 * 下载
 */

public class AI {
    // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
    static final String accessToken = "24.9657b8043319a037d3cb96ae933c3c42.2592000.1639986271.282335-25201686";

    /**
     * 动物识别
     */
    public static String animal(String imgFile) {
        // 请求animal识别的url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal";
        try {
            // 本地文件路径
           return Result(imgFile,url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 植物识别
     */
    public static String plant(String imgFile) {
        // 请求plant识别的url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant";
        try {
            // 本地文件路径
            return  Result(imgFile,url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private static String Result(String filePath, String url) throws Exception {
        byte[] imgData = FileUtil.readFileByBytes(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, StandardCharsets.UTF_8);
        String param = "image=" + imgParam;
        String result = HttpUtil.post(url, AI.accessToken, param);
        System.out.println(result);
        return result;
    }

   /* public static void main(String[] args) {
        plant("out/artifacts/WEB_war_exploded/uploadfiles/865a7acfe830551d8e5da981e7789529.jpg");
    }*/

}